// const filesInDirectory = dir =>
// 	new Promise(resolve =>
// 		dir.createReader().readEntries(entries => {
// 			Promise.all(
// 				entries
// 					.filter(e => e.name[0] !== ".")
// 					.map(e =>
// 						e.isDirectory
// 							? filesInDirectory(e)
// 							: new Promise(resolve => e.file(resolve))
// 					)
// 			)
// 				.then(files => [].concat(...files))
// 				.then(resolve)
// 		})
// 	)

// // 遍历插件目录，读取文件信息，组合文件名称和修改时间成数据
// const timestampForFilesInDirectory = dir =>
// 	filesInDirectory(dir).then(files =>
// 		files.map(f => f.name + f.lastModifiedDate).join()
// 	)

// // 刷新当前活动页
const reload = () => {
	console.debug('reload start: ', new Date())
	return new Promise(r=>{
		window.chrome.tabs.query(
			{
				active: true,
				currentWindow: true
			},
			tabs => {
				// NB: see https://github.com/xpl/crx-hotreload/issues/5
				if (tabs[0]) {
					window.chrome.tabs.reload(tabs[0].id)
				}
				// 强制刷新页面
				window.chrome.runtime.reload()
				r()
			}
		)
	})
}

// // 观察文件改动
// const watchChanges = (dir, lastTimestamp) => {
// 	timestampForFilesInDirectory(dir).then(timestamp => {
// 		// 文件没有改动则循环监听watchChanges方法
// 		if (!lastTimestamp || lastTimestamp === timestamp) {
// 			setTimeout(() => watchChanges(dir, timestamp), 1000) // retry after 1s
// 		} else {
// 			// 强制刷新页面
// 			reload()
// 		}
// 	})
// }

const installReload = () => {
	window.chrome.management.getSelf(self => {
		if (self.installType === "development") {
			let prevState = null
			let needUpdate = false
			let watchFiles = ()=>{
				console.debug('watching~')
				window.chrome.runtime.getPackageDirectoryEntry(async dir => {
					let getFiles = dir => {
						return new Promise(r => {
							dir.createReader().readEntries(es => {
								r(
									Promise.all(es.map(e => new Promise(r => {
										if (e.isDirectory) {
											r(getFiles(e))
										} else if (e.isFile) {
											e.file(r)
										}
									})))
								)
							})
						}).then(fs=>fs.flat())
					}
					if(!dir){
						setTimeout(watchFiles, 1000)
						return
					}
					let files = await getFiles(dir)
					let hasEssentialFile = true
					for(let n of ['manifest.json', 'style.css']){
						if(!files.find(f=>f.name === n)){
							hasEssentialFile = false
							break
						}
					}

					if(needUpdate && hasEssentialFile){
						await reload()
						needUpdate = false
					}

					let currentState = files.map(f=>`${f.name}${f.lastModified}`).join(',')
					if(prevState){
						// console.debug(prevState, currentState, prevState !== currentState, hasEssentialFile)
						if(prevState !== currentState){
							if(hasEssentialFile){
								// reload
								await reload()
							}else{
								needUpdate = true
							}
						}
					}
					prevState = currentState
					setTimeout(watchFiles, 1000)
				})
			}
			watchFiles()
		}
	})
}

export default installReload